﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Data;
using System.Collections;
using System.Globalization;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using ChineseSchool.BLL;

public partial class Util
{
    protected const string OAuthParameterPrefix = "oauth_";
    public static string HtmlStrip(string text)
    {
        text = Regex.Replace(text, @"<(.|\n)*?>", string.Empty);
        return text;
    }
    public static string JustAfter(string Str, string Seq, string SeqEnd)
    {
        string Orgi = Str;
        try
        {
            Str = Str.ToLower();
            Seq = Seq.ToLower();

            int i = Str.IndexOf(Seq);

            if (i < 0)
                return "";

            i = i + Seq.Length;

            int j = Str.IndexOf(SeqEnd, i);
            int end;

            if (j > 0) end = j - i;
            else end = Str.Length - i;

            return Orgi.Substring(i, end);
        }
        catch (Exception)
        {
            return "";
        }
    }
    public static string MD5(string password)
    {
        byte[] textBytes = System.Text.Encoding.Default.GetBytes(password);
        try
        {
            System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
            cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] hash = cryptHandler.ComputeHash(textBytes);
            string ret = "";
            foreach (byte a in hash)
            {
                if (a < 16)
                    ret += "0" + a.ToString("x");
                else
                    ret += a.ToString("x");
            }
            return ret;
        }
        catch
        {
            throw;
        }
    }
    public static string GenTitleUrl(string s)
    {
        return Encode.Uni2KD(Encode.ReplaceCharacter(HtmlStrip(s)));
    }
    public static string ExtractString(string source, int length)
    {
        string dest = String.Empty;
        if (length == 0 || source.Length == 0)
            return dest;
        if (source.Length < length)
            dest = source;
        else
        {
            string tmp = source.Substring(0, length);
            int nSub = tmp.Length - 1;
            while (tmp[nSub] != ' ')
            {
                nSub--;
                if (nSub == 0) break;
            }
            dest = tmp.Substring(0, nSub) + " ...";
        }
        return dest;
    }
    /// <summary>
    /// Tạo link chi tiết tin tức
    /// </summary>
    /// <param name="_id"></param>
    /// <param name="_title"></param>
    /// <returns></returns>
    public static string MakeLinkNewsDetail(string _id, string _title)
    {
        return string.Format("/tieng-trung/tin-tuc/{0}/{1}.html", _id, HtmlStrip(_title));
    }
    /// <summary>
    /// Tạo link chi tiết hoạt động
    /// </summary>
    /// <param name="_id"></param>
    /// <param name="_title"></param>
    /// <returns></returns>
    public static string MakeLinkActivitiesDetail(string _id, string _title)
    {
        return string.Format("/tieng-trung/hoat-dong/{0}/{1}.html", _id, HtmlStrip(_title));
    }
    public static string MakeLinkNewsTypeDetail(string _id, string _title)
    {
        return string.Format("/tieng-trung/nhom-tin/{0}/{1}.html", _id, HtmlStrip(_title));
    }
    public static string MakeLinkMenuInfo(string _id, string _title)
    {
        return string.Format("/tieng-trung/minh-a/{0}/{1}.html", _id, _title);
    }
    public static string MakeLinkMenuProInfo(string _id, string _title)
    {
        return string.Format("/tieng-trung/hoc-truc-tuyen/{0}/{1}.html", _id, _title);
    }
    /// <summary>
    /// Tạo link chi tiết bài học
    /// </summary>
    /// <param name="_id"></param>
    /// <param name="_title"></param>
    /// <returns></returns>
    public static string MakeLinkLessonDetail(string _id, string _title)
    {
        return string.Format("/tieng-trung/bai-hoc/{0}/{1}.html", _id, HtmlStrip(_title));
    }

    public static bool checkUserLogin()
    {
        string cookieName = "u_f_tmdt";
        HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
        if (cookie == null)
        {
            return false;
        }
        else
        {
            string name = "";
            string[] list = null;
            list = cookie.Value.ToString().Split(',');
            name = Encode.base64Decode(list[0].Trim());
            string key1 = list[1].Trim();
            string _key = MD5("489234" + name + "236");
            if (_key == key1)
                return true;
            else
                return false;
        }
    }

    public static string formatmoney(Decimal d)
    {
        return String.Format(CultureInfo.CreateSpecificCulture("vi-VN"), "{0:C}", d);
    }
    public static string ToSafeString(string str)
    {
        if (str.IndexOf("'") > -1)
        {
            str = str.Replace("'", "&#39;");
            str = str.Replace("=", "&#39;");
            str = str.Replace("script", " ");
            str = str.Replace("SCRIPT", " ");
            str = str.Replace("<", "{");
            str = str.Replace(">", "}");
        }
        return str;
    }
    public static string EncodePassword(string strPassword, string strFormat)
    {
        if (strFormat == "") { strFormat = "MD5"; }
        return FormsAuthentication.HashPasswordForStoringInConfigFile(strPassword, strFormat);
    }
    public static bool IsLogin()
    {
        if (HttpContext.Current.Session.Count > 0)
        {
            if (HttpContext.Current.Session["UserName"] != null && HttpContext.Current.Session["UserID"] != null)
            {
                // m_PK_iUserID = Convert.ToInt32(HttpContext.Current.Session["UserID"].ToString());
                return true;
            }
        }
        return false;
    }
    public static void FillDropDownList(ref DropDownList cboName, string TableName, string FieldValue, string FieldText, string strCond)
    {
        string strVL;
        DataTable dt = GetData("*", TableName, strCond).Tables[0];
        foreach (DataRow dr in dt.Rows)
        {
            string[] strValue = dr[FieldText].ToString().Split('|');
            if (HttpContext.Current.Session["Lang"] == null)
                strVL = strValue[0];
            else
                strVL = strValue[1];

            cboName.Items.Add(new ListItem(strVL, dr[FieldValue].ToString()));
        }
    }
    public static DataSet GetData(string ColumnName, string TableName, string Condition)
    {
        DataSet ds = new DataSet();
        try
        {
            objStr = "SELECT " + ColumnName + " FROM " + TableName + " WHERE " + Condition;
            SqlDataAdapter da = new SqlDataAdapter(objStr, Connection);
            da.Fill(ds, TableName);
            da.Dispose();
        }
        catch
        {
        }
        finally
        {
            if (Conn.State != ConnectionState.Closed)
            {
                Conn.Close();
            }
        }
        return ds;
    }

    public static DataSet GetData(string strSQL)
    {
        DataSet ds = new DataSet();
        try
        {
            objStr = strSQL;
            SqlDataAdapter da = new SqlDataAdapter(objStr, Connection);
            da.Fill(ds);
            da.Dispose();
        }
        catch { }
        finally
        {
            if (Conn.State != ConnectionState.Closed)
            {
                Conn.Close();
            }
        }
        return ds;
    }
    static string objStr;
    static SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    SqlCommand objCmd;
    public static SqlConnection Connection
    {
        get { return Conn; }
        set { Conn = value; }
    }
    public static DataSet GetData(string ColumnName, string TableName, string Condition, int StartRecord, int PageSize)
    {
        DataSet ds = new DataSet();
        objStr = "SELECT " + ColumnName + " FROM " + TableName + " WHERE " + Condition;
        SqlDataAdapter da = new SqlDataAdapter(objStr, new SqlConnection(ConfigurationSettings.AppSettings["DaukhiThienngaConnectionString"]));
        da.Fill(ds, StartRecord, PageSize, TableName);
        da.Dispose();
        return ds;
    }
    public static string RandomString(int length, bool LowerString, bool Number)
    {
        Random AppRandom = new Random((int)DateTime.Now.Ticks);
        string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        if (Number)
            str += "0123456789";
        if (LowerString)
            str += "abcdefghijklmnopqrstuvwxyz";

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++)
        {
            int r = AppRandom.Next(0, str.Length);
            sb.Append(str.Substring(r, 1));
        }
        return sb.ToString();
    }

    public static string RandomNumber(int length)
    {
        Random AppRandom = new Random((int)DateTime.Now.Ticks);
        DateTime MyDate = DateTime.Now;
        string MyStringDate = MyDate.ToString("yyyyMMdd");

        string str = "0123456789";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++)
        {
            int r = AppRandom.Next(0, str.Length);
            sb.Append(str.Substring(r, 1));
        }
        return sb.ToString() + MyStringDate.ToString();
    }

    public static class Alert
    {
    }
    public static void ShowMessage(string message)
    {
        // Cleans the message to allow single quotation marks
        string cleanMessage = message.Replace("'", "\\'");
        string script = "<script type=\"text/javascript\">alert('" + message + "');</script>";

        // Gets the executing web page
        Page page = HttpContext.Current.CurrentHandler as Page;

        // Checks if the handler is a Page and that the script isn't allready on the Page
        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
        {
            page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
        }
    }

    public static void WriteLog(string userName, int actionId, string content)
    {
        (new B_ActionLog()).SaveLog( userName,  actionId,  content);
    }

    public static bool CheckInteger(string param)
    {
        int value;
        if (int.TryParse(param, out value))
            return true;
        return false;
    }
}

